package at.ac.univie.zsu.aguataplan.video;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import at.ac.univie.zsu.aguataplan.exception.FileHandlingException;
import at.ac.univie.zsu.aguataplan.exception.FtpHandlingException;
import at.ac.univie.zsu.aguataplan.exception.VideoHandlingException;
import at.ac.univie.zsu.aguataplan.property.SystemProperties;
import at.ac.univie.zsu.aguataplan.ui.ProgressListener;
import at.ac.univie.zsu.aguataplan.util.Constants;
import at.ac.univie.zsu.aguataplan.video.util.FileHandling;
import at.ac.univie.zsu.aguataplan.video.util.FtpHandling;
import at.ac.univie.zsu.aguataplan.video.util.ThreadFtp;
import at.ac.univie.zsu.aguataplan.video.util.ThreadLocal;

/**
 * @author gerry
 * 
 */
@Configurable
public class VideoServiceBean implements VideoService, Constants, IVideoService {
	private static Logger log = Logger.getLogger(VideoServiceBean.class);

	private List<ProgressListener> pl;

	private ThreadFtp ftpCopy;
	private ThreadLocal localCopy;

	private int progressFtp;
	private int progressFile;

	private String newFileOutput;

	@Autowired
	private SystemProperties systemProp;

	// ----------------------------------------------------
	// CONSTRUCTOR
	// ----------------------------------------------------

	public VideoServiceBean() {
		pl = new ArrayList<ProgressListener>();
		this.progressFile = NOT_INITIALIZED;
	}

	// ----------------------------------------------------
	// METHODS PRIVATE
	// ----------------------------------------------------

	private String createOutputFileName(String name) {
		String s;
		String prefix = systemProp.getVideoPrefix();
		String postfix = "postfix";

		if (systemProp.getVideoPostfix().equals(POSTFIX_DATE)) {
			SimpleDateFormat sdf = new SimpleDateFormat(systemProp.getVideoPostfixType());
			postfix = sdf.format(new Date());
		}

		s = prefix + "_" + postfix + "_" + name;

		return s;
	}

	private synchronized void informProgressListener() {
		for (ProgressListener p : pl) {
			p.setProgress(Math.min(progressFtp, progressFile));
		}

	}

	// ----------------------------------------------------
	// IVideoService
	// ----------------------------------------------------

	@Override
	public void setProgressFtp(int progress) {
		this.progressFtp = progress;

		informProgressListener();
	}

	@Override
	public synchronized void setProgressFile(int progress) {
		this.progressFile = progress;

		informProgressListener();
	}

	// ----------------------------------------------------
	// METHODS
	// ----------------------------------------------------

	public void insertVideo(String dirInput, String fileInput) throws VideoHandlingException {
		int retValThread;

		newFileOutput = createOutputFileName(fileInput);

		ftpCopy = new ThreadFtp(this, dirInput, fileInput, systemProp.getFtpServerDir(), newFileOutput,
				systemProp.getFtpServerAddress(), systemProp.getFtpServerPort(), systemProp.getFtpServerUser(),
				systemProp.getFtpServerPassword());
		localCopy = new ThreadLocal(this, dirInput, fileInput, systemProp.getDirVideo(), newFileOutput);

		ftpCopy.start();
		localCopy.start();

		try {
			localCopy.join();
			ftpCopy.join();
		} catch (InterruptedException e) {

			log.error(e.toString());
			throw new VideoHandlingException(e.toString(), RET_ERR_INTERRUPTED);
		}

		// if there is a problem with ftp copy also delete local copy
		if ((retValThread = ftpCopy.getRetValue()) != RET_OK) {
			int retVal;
			log.error("could not copy ftp: " + retValThread);
			retVal = localCopy.delFile();
			log.error("try to delete file " + fileInput + ": Code: " + retVal);
			throw new VideoHandlingException("could not store video", retValThread);
		}

		// if there is a problem with local copy also delete it on ftp copy
		if ((retValThread = localCopy.getRetValue()) != RET_OK) {
			int retVal;
			log.error("could not copy local: " + retValThread);
			retVal = ftpCopy.delFile();
			log.error("try to delete file on ftp " + fileInput + ": Code: " + retVal);
			throw new VideoHandlingException("could not store video", retValThread);
		}

		this.progressFile = NOT_INITIALIZED;

	}

	@Override
	public void deleteVideo(String file) throws VideoHandlingException {
		// ftp
		deleteVideoFtp(file);

		// file
		deleteVideoLocal(file);
	}

	@Override
	public void deleteVideoLocal(String file) throws VideoHandlingException {
		FileHandling fileHandling = new FileHandling(this);
		try {
			fileHandling.delFile(systemProp.getDirVideo(), file);
		} catch (FileHandlingException e) {
			throw new VideoHandlingException("could not delete local video", e.getStatus());
		}

	}

	@Override
	public void deleteVideoFtp(String file) throws VideoHandlingException {
		FtpHandling ftpHandling = new FtpHandling(this, systemProp.getFtpServerAddress(),
				systemProp.getFtpServerPort(), systemProp.getFtpServerUser(), systemProp.getFtpServerPassword());

		try {
			ftpHandling.delete(systemProp.getFtpServerDir(), file);
		} catch (FtpHandlingException e) {
			throw new VideoHandlingException("could not delete ftp video", e.getStatus());
		}

	}

	@Override
	public void downloadVideo(String file) throws VideoHandlingException {
		FtpHandling fh = new FtpHandling(this, systemProp.getFtpServerAddress(), systemProp.getFtpServerPort(),
				systemProp.getFtpServerUser(), systemProp.getFtpServerPassword());

		try {
			fh.download(systemProp.getFtpServerDir(), file, systemProp.getDirVideo(), file);
		} catch (FtpHandlingException e) {
			throw new VideoHandlingException("could not delete local video", e.getStatus());
		}
	}

	@Override
	public void registerProgressListener(ProgressListener progressListener) {
		pl.add(progressListener);

	}

	@Override
	public String getVideoNameInserted() {
		return this.newFileOutput;
	}

	// ----------------------------------------------------
	// GETTER & SETTER
	// ----------------------------------------------------

	public SystemProperties getSystemProp() {
		return systemProp;
	}

	public void setSystemProp(SystemProperties systemProp) {
		this.systemProp = systemProp;
	}

}
